from PIL import Image
from PIL import ImageFilter
import matplotlib.pyplot as plt
import cv2 as cv
from functools import wraps
import os

#函数装饰器
def log(save_path):
    def decorator(func):
        @wraps(func)
        def wrapper(*args,**kwargs):
            #去除文件名，获取路径
            folder = os.path.dirname(save_path)
            if os.path.exists(folder):
                print("Correct path!")
            else:
                print("False path!")
                #系统自动创建文件夹
                os.makedirs(folder)
                print("The new path has been created")      
            return func(*args,**kwargs)
        return wrapper
    return decorator


#类装饰器
class imgdecorator:
    def __init__(self,image_path):
        self.image_path = image_path
    def __call__(self,func):
        @wraps(func)
        #获取图片的H,S,V
        def wrapper(*args,**kwargs):
            img=cv.imread(self.image_path)
            height,weight,_=img.shape
            hsv=cv.cvtColor(img, cv.COLOR_BGR2HSV)
            H,S,V=cv.split(hsv)
            bright=cv.mean(V)[0]
            saturation=cv.mean(S)[0]
            print("image size:({0},{1})".format(height,weight))
            print("image brightness:{}".format(bright,))
            print("image saturation:{}".format(saturation,))
            #执行被修饰函数
            result=func(*args,**kwargs)
            return result
        return wrapper

@imgdecorator(r"C:\Users\User\Desktop\code\pycode\lab8\saveimg\poqi.jpg")
class ImageProcessor:#基类
    def __init__(self,image_path):
        self.image_path = image_path
    #打开图片
    def open_img(self):
        img = Image.open(self.image_path)
        return img
    #灰化
    def Grayscalepro(self):
        image_filtered = self.open_img().filter(ImageFilter.BLUR)
        return image_filtered
    #裁剪或调整大小
    def tailor(self,parameter_list):
        if len(parameter_list) == 4:#box
            resize = self.open_img().crop(parameter_list)
            return resize
        else:#resize
            region = self.open_img().resize(parameter_list)
            return region
    #边缘锐化
    def edge_extraction(self):#边缘锐化
        return self.open_img().filter(ImageFilter.FIND_EDGES)
    #模糊化
    def dim(self):
        return self.open_img().convert('1')
    #保存,img为处理后的函数
    @log(r"C:\Users\User\Desktop\code\pycode\lab8\saveimg\false\test.jpg")
    def save_img(self,img,save_path):
        return img.save(save_path)
    
img1=ImageProcessor(r"C:\Users\User\Desktop\code\pycode\lab8\saveimg\poqi.jpg")
img2=img1.edge_extraction()
img1.save_img(img2,r"C:\Users\User\Desktop\code\pycode\lab8\saveimg\false\test.jpg")
